package com.thunisoft.netty.http;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;

/**
 * @title NettyHttpUtils.java
 * @package com.thunisoft.netty.http
 * @projectName spring.boot
 * @author yzj
 * @date 2019年10月8日 下午3:03:15
 */
public class NettyHttpUtils {

	private static final boolean KEEP_ALIVE = true;
	private static final boolean CLOSE = false;

	public static void sendResponse(ChannelHandlerContext ctx, HttpRequest request, boolean keepAlive,
			FullHttpResponse response) {
		response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); // 设置响应长度
		if (keepAlive) {
			if (!request.protocolVersion().isKeepAliveDefault()) {
				response.headers().set(HttpHeaderNames.CONNECTION, KEEP_ALIVE);
			}
		} else {
			response.headers().set(HttpHeaderNames.CONNECTION, CLOSE);
		}
		ChannelFuture f = ctx.writeAndFlush(response);
		if (!keepAlive) {
			f.addListener(ChannelFutureListener.CLOSE);
		}
	}
}
